package com.dge.common.utils

import android.annotation.SuppressLint
import android.app.ActivityManager
import android.content.Context
import android.content.pm.ApplicationInfo
import android.content.res.Configuration
import android.content.res.Resources
import android.graphics.Color
import android.location.LocationManager
import android.os.Build
import android.text.TextUtils
import android.view.View
import android.view.Window
import android.view.WindowManager
import android.widget.EditText
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.recyclerview.widget.RecyclerView
import com.dge.common.R
import com.dge.common.common.CountDownButtonHelper
import com.dge.common.extentions.applyStretchEdgeEffect
import com.dge.common.extentions.isVisibleOnScreen
import com.zackratos.ultimatebarx.ultimatebarx.java.Operator
import com.zackratos.ultimatebarx.ultimatebarx.java.UltimateBarX
import okhttp3.internal.toHexString
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import timber.log.Timber
import java.io.*
import java.lang.Integer.parseInt
import java.math.BigDecimal
import java.net.InetAddress
import java.text.DecimalFormat
import java.text.NumberFormat
import java.text.SimpleDateFormat
import java.util.*

object Utils {
    val TAG = "Utils"

    //设置界面全屏
    fun setFullScreenWindowLayout(window: Window) {
        window.decorView.systemUiVisibility =
            View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE //or 和java的 | 符号一样
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
        window.statusBarColor = Color.TRANSPARENT
        //设置页面全屏显示
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            val layoutParams = window.attributes
            layoutParams.layoutInDisplayCutoutMode =
                WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
            window.attributes = layoutParams
        }
    }

    fun setImmersiveStatusOrNavBar(
        activity: FragmentActivity,
        fitWindow: Boolean,
        isLight: Boolean,
        applyNav: Boolean
    ) {
        setImmersiveStatusOrNavBarBase(activity, fitWindow, isLight, applyNav)
    }

    private fun setImmersiveStatusOrNavBarBase(
        fragmentOrActivity: Any,
        fitWindow: Boolean,
        isLight: Boolean,
        applyNav: Boolean
    ) {
        if (fragmentOrActivity !is Fragment && fragmentOrActivity !is FragmentActivity) {
            return
        }
        val operator: Operator = if (fragmentOrActivity is FragmentActivity) {
            if (applyNav)
                UltimateBarX.statusBar(fragmentOrActivity)
                    .fitWindow(fitWindow)
            else
                UltimateBarX.statusBarOnly(fragmentOrActivity)
                    .fitWindow(fitWindow)
        } else {
            if (applyNav)
                UltimateBarX.statusBar(fragmentOrActivity as Fragment)
                    .fitWindow(fitWindow)
            else
                UltimateBarX.statusBarOnly(fragmentOrActivity as Fragment)
                    .fitWindow(fitWindow)
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (fitWindow) {
                operator.color(Color.TRANSPARENT)
            } else
                operator.transparent()
        } else {
            if (isLight) {
                operator.colorRes(R.color.alphaBlack)
            } else {
                if (fitWindow) {
                    operator.color(Color.TRANSPARENT)
                } else
                    operator.transparent()
            }
        }
    }

    fun setImmersiveStatusBar(
        fragmentActivity: FragmentActivity,
        colorRes: Int = R.color.white,
        isLight: Boolean = true,
        fitWindow: Boolean = true//默认不沉浸式
    ) {
        UltimateBarX.statusBarOnly(fragmentActivity)
            .colorRes(colorRes)
            .light(isLight)
            .fitWindow(fitWindow)
            .apply()
    }

    fun setImmersiveStatusOrNavBar(
        fragment: Fragment,
        fitWindow: Boolean,
        isLight: Boolean,
        applyNav: Boolean
    ) {
        setImmersiveStatusOrNavBarBase(fragment, fitWindow, isLight, applyNav)
    }

    /**
     * @param button        按钮控件
     * @param defaultString 按钮上默认的字符串
     * @param tmpString     计时时显示的字符串
     * @param max           失效时间（单位：s）
     * @param interval      更新间隔（单位：s）
     * @function 在按钮上启动一个定时器
     */
    fun startTimer(
        button: TextView?,
        defaultString: String?,
        tmpString: String?,
        max: Int,
        interval: Int,
        onFinished: (() -> Unit)? = null
    ) {
        val timer = CountDownButtonHelper(
            button,
            defaultString, tmpString, max, interval
        )
        timer.setOnFinishListener {
            if (onFinished != null) {
                onFinished()
            }
        }
        timer.start()
    }

    fun formatNumber(num: Long): String {
        if (num < 10000) {
            return num.toString() + ""
        }
        val df = DecimalFormat("######0.0")
        val d = num / 10000.0
        return df.format(d) + "万"
    }

    /**
     * double保留两位小数，并且不使用科学计数法
     */
    fun saveTwoDecimals(num: Double): String {
        val instance = NumberFormat.getInstance()
        instance.isGroupingUsed = false //设置不使用科学计数法
        instance.maximumFractionDigits = 2 //小数点最大位数
        return instance.format(num)
    }

    /**
     * @param phoneNumber 手机号
     * @return 有效则返回true, 无效则返回false
     * @function 判断手机号是否有效
     */
    fun validPhoneNumber(countryCode: String, phoneNumber: String): Boolean {
        return if (countryCode == "86") phoneNumber.length == 11 && phoneNumber.matches(Regex("[0-9]{1,}")) else phoneNumber.matches(
            Regex("[0-9]{1,}")
        )
    }

    /**
     * 判断该进程ID是否属于该进程名
     * @param context
     * @param pid 进程ID
     * @param p_name 进程名
     * @return true属于该进程名
     */
    fun isPidOfProcessName(context: Context, pid: Int, p_name: String?): Boolean {
        if (p_name == null) return false
        var isMain = false
        val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        //遍历所有进程
        for (process in am.runningAppProcesses) {
            if (process.pid == pid) {
                //进程ID相同时判断该进程名是否一致
                if (process.processName == p_name) {
                    isMain = true
                }
                break
            }
        }
        return isMain
    }

    /**
     * 装换为万或亿为结尾
     *
     * @param amount 结果
     * @return
     */
    fun formatWanYiNumber(amount: BigDecimal?): String {
        val UNIT_STRING_WAN = "万"
        val UNIT_STRING_YI = "亿"
        if (amount == null) {
            return "0"
        }
        if (amount < BigDecimal(10000)) {
            //如果小于1万
            return amount.stripTrailingZeros().toPlainString()
        }
        if (amount < BigDecimal(100000000)) {
            //如果大于1万小于1亿
            return amount.divide(BigDecimal(10000), 2, BigDecimal.ROUND_DOWN).stripTrailingZeros()
                .toPlainString()
                .toString() + UNIT_STRING_WAN
        }
        return amount.divide(BigDecimal(100000000), 2, BigDecimal.ROUND_DOWN).stripTrailingZeros()
            .toPlainString()
            .toString() + UNIT_STRING_YI
    }

    fun getTimeMillsFromString(time: String, format: String = "yyyy-MM-dd HH:mm:ss"): Long {
        var newString = time
        if (time.contains("T") && time.contains(".")) {
            newString = newString.replace("T", " ").split(".")[0]
        }
        // "yyyy-MM-dd HH:mm:ss"
        val format = SimpleDateFormat(format);
        val date = format.parse(newString);
        //日期转时间戳（毫秒）
        val mills = date.getTime()
        return mills
    }

    fun getTime(
        date: Date = Date(System.currentTimeMillis()),
        pattern: String = "yyyy-MM-dd"
    ): String {
        val formatter = SimpleDateFormat(pattern)
        return formatter.format(date)
    }

    fun getyyyyMMTime(
        date: Date = Date(System.currentTimeMillis()),
        pattern: String = "yyyy-MM"
    ): String {
        val formatter = SimpleDateFormat(pattern)
        return formatter.format(date)
    }

    fun getLastMonth(
        timeMills: Long = System.currentTimeMillis(),
        pattern: String = "yyyy-MM"
    ): String {
        val sdf = SimpleDateFormat(pattern)
        val date = Date(timeMills)
        val cal = Calendar.getInstance()
        cal.time = date
        cal.add(Calendar.MONTH, -1)
        val lastMonth = cal.time
        return sdf.format(lastMonth)
    }

    /***
     * 日期大小比较
     */
    fun dataComparison(currentData: String, comparisonData: String, pattern: String = "yyyy-MM"): Int {
        val sdf = SimpleDateFormat(pattern)

        return if ((sdf.parse(currentData)?.time ?: 0) > (sdf.parse(comparisonData)?.time ?: 0)) {
            1
        } else if ((sdf.parse(currentData)?.time ?: 0) < (sdf.parse(comparisonData)?.time ?: 0)) {
            -1
        } else {
            0
        }
    }

    fun getLastYearMonth(
        timeMills: Long = System.currentTimeMillis(),
        pattern: String = "yyyy-MM"
    ): String {
        val sdf = SimpleDateFormat(pattern)
        val date = Date(timeMills)
        val cal = Calendar.getInstance()
        cal.time = date
        cal.add(Calendar.YEAR, -1)
        val lastMonth = cal.time
        return sdf.format(lastMonth)
    }

    fun stringToLongTime(
        time: String,
        pattern: String = "yyyy-MM"
    ): Long {
        val sdf = SimpleDateFormat(pattern)
        return sdf.parse(time)?.time ?: 0
    }

    fun getNextMonth(
        timeMills: Long = System.currentTimeMillis(),
        pattern: String = "yyyy-MM"
    ): String {
        val sdf = SimpleDateFormat(pattern)
        val date = Date(timeMills)
        val cal = Calendar.getInstance()
        cal.time = date
        cal.add(Calendar.MONTH, +1)
        val lastMonth = cal.time
        return sdf.format(lastMonth)
    }

    fun getTimeDistance(beginData: Date, endData: Date): Long {
        var fromCalendar = Calendar.getInstance()
        fromCalendar.time = beginData
        var currentCalendar = Calendar.getInstance()
        currentCalendar.time = endData
        return (currentCalendar.timeInMillis - fromCalendar.timeInMillis) / (1000 * 3600 * 24)
    }

    object EditTextUtil {
        /*** 小数点后的位数  */
        private const val POINTER_LENGTH = 2
        private const val POINTER = "."
        private const val ZERO = "0"
        private var number: String? = null
        private var curSelection = 0

        /***
         * 保留两位小数
         * @param editText
         * @param length 整数数字长度
         */
        @SuppressLint("SetTextI18n")
        fun keepTwoDecimals(editText: EditText, length: Int) {
            number = editText.text.toString()
            //第一位不能输入小点
            if (number!!.length == 1 && TextUtils.equals(
                    number!!.substring(0, 1),
                    POINTER
                )
            ) {
                editText.setText("")
                return
            }
//            if(number!!.toInt()>=50){
//                ToastUtils.showLong("提现金额最大为50")
//                editText.setText("50")
//            }
//            if(number!!.toInt()<=10){
//                ToastUtils.showLong("提现金额最小为10")
//                editText.setText("10")
//            }
            //第一位0时，后续不能输入其他数字
            if (number!!.length > 1 && TextUtils.equals(
                    number!!.substring(0, 1),
                    ZERO
                ) &&
                !TextUtils.equals(number!!.substring(1, 2), POINTER)
            ) {
                editText.setText(number!!.substring(0, 1))
                editText.setSelection(editText.length())
                return
            }
            val numbers = number!!.split("\\.").toTypedArray()
            //已经输入小数点的情况下
            if (numbers.size == 2) {
                //小数处理
                val decimalsLength = numbers[1].length
                if (decimalsLength > POINTER_LENGTH) {
                    curSelection = editText.selectionEnd
                    editText.setText(number!!.substring(0, numbers[0].length + 1 + POINTER_LENGTH))
                    editText.setSelection(if (curSelection > number!!.length) number!!.length else curSelection)
                }
                //整数处理
                if (numbers[0].length > length) {
                    curSelection = editText.selectionEnd
                    editText.setText(number!!.substring(0, length) + number!!.substring(length + 1))
                    editText.setSelection(if (curSelection > length) length else curSelection)
                }
            } else {
                //整数处理
                if (editText.length() > length) {
                    if (number!!.contains(POINTER)) return
                    curSelection = editText.selectionEnd
                    editText.setText(number!!.substring(0, length))
                    editText.setSelection(if (curSelection > length) length else curSelection)
                }
            }
        }
    }

    object FontCompatUtils {
        const val MAX_FONT_SCALE = 1.00f //可自行修改最大缩放值
        const val TAG = "FontCompatUtils"
        private var fontScalePercent: Float? = null
        fun getResources(res: Resources): Resources {
            val configuration: Configuration = res.getConfiguration()
            if (fontScalePercent == null) {
                fontScalePercent = 1 / configuration.fontScale
            }
            if (shouldChangeFontScale(configuration)) { //非默认值
                val newConfig = Configuration()
                newConfig.setToDefaults() //设置默认
//                configuration.fontScale = MAX_FONT_SCALE;
                res.updateConfiguration(newConfig, res.getDisplayMetrics())
            }
            return res
        }

        /**
         * 是否需要改变字体缩放级别
         *
         * @param configuration
         * @return
         */
        fun shouldChangeFontScale(configuration: Configuration): Boolean {
            return configuration.fontScale > MAX_FONT_SCALE
        }

        /**
         * 字体缩放比例
         *
         * @return
         */
        fun getFontScalePercent(): Float? {
            return if (fontScalePercent == null) {
                1f
            } else fontScalePercent
        }
    }

    fun getTime(timeMills: Long): String? {
        val sec = (timeMills / 1000 % 60).toInt()
        val min = (timeMills / 1000 / 60 % 60).toInt()
        val hour = (timeMills / 1000 / 60 / 60).toInt()
        if (hour > 0) {
            if (hour >= 100) {
                return java.lang.String.format(
                    Locale.CHINESE,
                    "%1$03d:%2$02d:%3$02d",
                    hour,
                    min,
                    sec
                )
            } else {
                return java.lang.String.format(
                    Locale.CHINESE,
                    "%1$02d:%2$02d:%3$02d",
                    hour,
                    min,
                    sec
                )
            }
        } else {
            return java.lang.String.format(Locale.CHINESE, "%1$02d:%2$02d", min, sec)
        }
    }

    fun listToString(mList: List<String>): String {
        val SEPARATOR = ","
        val sb = StringBuilder()
        var convertedListStr: String
        return if (mList.isNotEmpty()) {
            for (item in mList) {
                sb.append(item)
                sb.append(SEPARATOR)
            }
            convertedListStr = sb.toString()
            convertedListStr =
                convertedListStr.substring(0, convertedListStr.length - SEPARATOR.length)
            convertedListStr
        } else ""
    }

    fun isLetterDigit(str: String): Boolean {
        var isDigit: Boolean = false
        var isLetter: Boolean = false
        var isLength: Boolean = false
        if (str.length >= 6) {
            isLength = true
        }
        if (isLength) {
            for (value in str.indices) {
                if (Character.isDigit(value)) {
                    isDigit = true;
                } else if (Character.isLetter(value)) {
                    isLetter = true
                }
            }
        }
        val isRight = isDigit && isLetter && isLength
        return isRight
    }

    /**
     * 手机是否开启位置服务，如果没有开启那么所有app将不能使用定位功能
     */
    fun isLocServiceEnable(context: Context): Boolean {
        val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
        val gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
        val network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
        return gps || network
    }

    fun dataDigit(digit: Int, `in`: Double): Double {
        return BigDecimal(`in`).setScale(digit, BigDecimal.ROUND_HALF_UP).toDouble()
    }

    fun formatStackTrace(throwable: Throwable?): String {
        if (throwable == null) return ""
        var rtn = throwable.stackTrace.toString()
        try {
            val writer: Writer = StringWriter()
            val printWriter = PrintWriter(writer)
            throwable.printStackTrace(printWriter)
            printWriter.flush()
            writer.flush()
            rtn = writer.toString()
            printWriter.close()
            writer.close()
        } catch (e: IOException) {
            e.printStackTrace()
        } catch (ex: java.lang.Exception) {
        }
        return rtn
    }

    /**
     * ArrayList取交集
     */
    fun <T> intersection(list1: ArrayList<T>, list2: ArrayList<T>): ArrayList<T> {
        val list3 = list1.clone() as ArrayList<T>
        val list4 = list2.clone() as ArrayList<T>
        list3.retainAll(list4)
        return list3
    }

    /**
     * ArrayList取去重并集
     */
    fun <T> deduplicationUnion(list1: ArrayList<T>, list2: ArrayList<T>): ArrayList<T> {
        val list5 = list1.clone() as ArrayList<T>
        val list6 = list2.clone() as ArrayList<T>
        list6.removeAll(list5)
        list5.addAll(list6)
        return list5
    }

    /**
     * ArrayList取可重复并集
     */
    fun <T> duplicationUnion(list1: ArrayList<T>, list2: ArrayList<T>): ArrayList<T> {
        val list5 = list1.clone() as ArrayList<T>
        val list6 = list2.clone() as ArrayList<T>
        list5.addAll(list6)
        return list5
    }

    /**
     * ArrayList取差集A-B
     */
    fun <T> subtractionAmB(a: ArrayList<T>, b: ArrayList<T>): ArrayList<T> {
        val list1 = a.clone() as ArrayList<T>
        val list2 = b.clone() as ArrayList<T>
        list1.removeAll(list2.toSet())
        return list1
    }

    /**
     * ArrayList取差集B-A
     */
    fun <T> subtractionBmA(a: ArrayList<T>, b: ArrayList<T>): ArrayList<T> {
        val list1 = a.clone() as ArrayList<T>
        val list2 = b.clone() as ArrayList<T>
        list2.removeAll(list1.toSet())
        return list2
    }

    /**
     * 应用 android12 RecyclerView 过度滚动果冻效果
     */
    fun applyRvStretchEdgeEffect(
        recyclerView: RecyclerView,
        @RecyclerView.Orientation orientation: Int = RecyclerView.VERTICAL
    ) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) {
            recyclerView.applyStretchEdgeEffect(orientation)
        }
    }

    /**
     * 判断当前view是否在屏幕可见
     * @param needDoubleCheck 是否需要二次检查
     */
    fun isVisibleOnScreen(view: View, needDoubleCheck: Boolean = false): Boolean {
        return view.isVisibleOnScreen(needDoubleCheck)
    }

    /**
     * 计算两个颜色的色调差异，如果小于500，则这两个颜色色调相近，需建议调整为更强对比的颜色，以改善用户体验
     */
    fun getColorToneDifference(bgColor: String, icColor: String): Int {
        val bg = Color.parseColor(bgColor)
        val bgRed: Int = bg and 0xff0000 shr 16
        val bgGreen: Int = bg and 0x00ff00 shr 8
        val bgBlue: Int = bg and 0x0000ff
        val ic = Color.parseColor(icColor)
        val icRed: Int = ic and 0xff0000 shr 16
        val icGreen: Int = ic and 0x00ff00 shr 8
        val icBlue: Int = ic and 0x0000ff
        return bgRed - icRed + bgGreen - icGreen + bgBlue - icBlue
    }

    /**
     * 计算一个颜色的互补色
     */
    fun getComplementaryColor(color: String): String {
        val ic = Color.parseColor(color)
        val icRed: Int = 255 - (ic and 0xff0000 shr 16)
        val icGreen: Int = 255 - (ic and 0x00ff00 shr 8)
        val icBlue: Int = 255 - (ic and 0x0000ff)
        return "#" + Color.rgb(icRed, icGreen, icBlue).toHexString().substring(2)
    }

    /**
     * 获取一个颜色的对比色
     * @param color
     * @param step 跨越的色值，取值应在 -15到15之前，太大会导致颜色边白色，太小会导致颜色变黑色。-5或5应该是一个比较合适的值
     */
    fun getContrastingColor(color: String, step: Int): String {
        val asHex = listOf("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F")
        var sRslt = "#"
        var iTemp = 0
        for (i in 1..6) {
            iTemp = parseInt(color[i].toString(), 16) + step
            if (iTemp > 15) iTemp = 15
            if (iTemp < 0) iTemp = 0
            sRslt += asHex[iTemp]
        }
        return sRslt
    }

    /**
     * 获取手机支持的CPU架构
     */
    fun getABIs(): String {
        val abis = Build.SUPPORTED_ABIS
        val abiStr = StringBuilder()
        abis.forEach {
            abiStr.append(it)
            abiStr.append(',')
        }
        Timber.i("CPU架构: $abiStr")
        return abiStr.toString()
    }

    /**
     * 判断当前应用是否是debug状态：debuggable为false的状态
     */
    fun isApkInDebug(context: Context): Boolean {
        return try {
            val info = context.applicationInfo
            info.flags and ApplicationInfo.FLAG_DEBUGGABLE != 0
        } catch (e: java.lang.Exception) {
            false
        }
    }

    /**
     * 深克隆，需要T实现Serializable接口
     */
    fun <T> deepClone(list: ArrayList<T>): ArrayList<T>? {
        var out: ObjectOutputStream? = null
        var `in`: ObjectInputStream? = null
        try {
            //写入流
            val byteout = ByteArrayOutputStream()
            out = ObjectOutputStream(byteout)
            out.writeObject(list)
            //输出流到内存
            val byteIn = ByteArrayInputStream(byteout.toByteArray())
            `in` = ObjectInputStream(byteIn)
            return `in`.readObject() as ArrayList<T>
        } catch (e: Exception) {
            e.printStackTrace()
            return null
        } finally {
            try {
                out?.close()
            } catch (e: Exception) {
            }
            try {
                `in`?.close()
            } catch (e: Exception) {
            }
        }
    }

    /**
     * 深克隆，需要V实现Serializable接口
     */
    fun <K, V> deepClone(map: HashMap<K, V>): HashMap<K, V>? {
        var out: ObjectOutputStream? = null
        var `in`: ObjectInputStream? = null
        try {
            //写入流
            val byteout = ByteArrayOutputStream()
            out = ObjectOutputStream(byteout)
            out.writeObject(map)
            //输出流到内存
            val byteIn = ByteArrayInputStream(byteout.toByteArray())
            `in` = ObjectInputStream(byteIn)
            return `in`.readObject() as HashMap<K, V>
        } catch (e: Exception) {
            e.printStackTrace()
            return null
        } finally {
            try {
                out?.close()
            } catch (e: Exception) {
            }
            try {
                `in`?.close()
            } catch (e: Exception) {
            }
        }
    }

    /**
     * 打印格式化的json数据
     */
    fun printJson(tag: String, msg: String) {
        val lineSeparator = System.getProperty("line.separator")
        val message: String = try {
            if (msg.startsWith("{")) {
                val jsonObject = JSONObject(msg)
                jsonObject.toString(4) //最重要的方法，就一行，返回格式化的json字符串，其中的数字4是缩进字符数
            } else if (msg.startsWith("[")) {
                val jsonArray = JSONArray(msg)
                jsonArray.toString(4)
            } else {
                msg
            }
        } catch (e: JSONException) {
            msg
        }
        // message = headString + LINE_SEPARATOR.toString() + message
        val lines: Array<String> = message.split(lineSeparator).toTypedArray()
        // val sb = StringBuilder()
        for (line in lines) {
            Timber.tag(tag).i(line)
            // sb.append(line).append("\n")
            // Log.d(tag, "║ $line")
        }
        // return sb.toString()
    }

    fun isImageFromFileExtension(extension: String): Boolean {
        var extensionLower = extension
        if (TextUtils.isEmpty(extensionLower)) {
            return false
        }
        extensionLower = extensionLower.lowercase(Locale.getDefault())
        when (extensionLower) {
            "jpg", "jpeg", "gif", "png", "bmp", "webp" -> return true
        }
        return false
    }

    /**
     * 是否是64位架构CPU
     */
    fun is64bitCPU(): Boolean {
        val abis = getABIs()
        return abis.contains("arm64") || abis.contains("aarch64")
    }

    /**
     * host 是否ping的通
     */
    fun isAvailableByPing(host: String): Boolean {
        var status = false
        try {
            status = InetAddress.getByName(host).isReachable(1500)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        Timber.i("isAvailableByPing host = $host, status = $status")
        return status
    }
}

